auto.waitFor()
setScreenMetrics(1080, 1920);

//launchApp("消灭星星经典版");

// var red_img="/sdcard/红色左右.png";
// var yellow_img="/sdcard/红色左右.png";
// var blue_img="/sdcard/红色左右.png";
// var zise_img="/sdcard/红色左右.png";

var red_img="./红球.png";
var yellow_img="./黄球.png";
var blue_img="./篮球.png";
var zise_img="./紫球.png";
var lvse_img="./绿球.png";

// 请求截图
if(!requestScreenCapture()){
    toastLog("请求截图失败");
    exit();
}

//sleep(3000)
//waitForActivity("消灭星星经典版")

//longClick(16,1695);

console.clear();

var repeatNum = 0
while(true){
    
    repeatNum++;
    if(repeatNum>10){
        exit();
    }
    //click(16,1695);
    
    if(get_mainqiu(red_img)){
        find_pic_clickmax(red_img)
        sleep(1000)
    }

    if(get_mainqiu(yellow_img)){
        find_pic_clickmax(yellow_img)
        sleep(1000)
    }

    if(get_mainqiu(blue_img)){
        find_pic_clickmax(blue_img)
        sleep(1000)
    }

    if(get_mainqiu(zise_img)){
        find_pic_clickmax(zise_img)
        sleep(1000)
    }

    if(get_mainqiu(lvse_img)){
        find_pic_clickmax(lvse_img)
        sleep(1000)
    }

    exit();
}

function get_mainqiu(p){
//529 1540
    temp1 = images.read(p)
    img1 = captureScreen()
    p1 = findImage(img1, temp1, 
        {
            region: [490, 1490, 90, 90],
            threshold:0.6
        }
    )
    if(p1){
        log("找到主球"+p+"："+p1.x+":"+p1.y)
        //click(p1.x+temp1.getWidth()/2,p1.y+ temp1.getHeight()/2)
        //sleep(100)
        return true
    }else{
        //log("没找到："+p);
        return false
    }
    


    // //1605-1485 = 120
    // var result = images.matchTemplate(img1, temp1, {
    //     region: [0, 1485, device.width, 120],
    //     //max: 100,
    //     threshold:0.6
    // });
}

function find_pic_clickmax(p){
    temp1 = images.read(p)
    img1 = captureScreen()
    // p1 = findImage(img1, temp1, 
    //     {
    //         region: [0, 0, device.width, 1464],
    //         threshold:0.6
    //     }
    // )
    var result = images.matchTemplate(img1, temp1, {
        region: [0, 0, device.width, 1379],
        max: 100,
        threshold:0.6
    });
    
    var findx=0,findy=0;
    result.matches.forEach(match => {
        //log("point = " + match.point + ", similarity = " + match.similarity);
        //findx = match.point
        if(match.point.y>=findy){
            findx = match.point.x
            findy = match.point.y
            //log("找到了2"+p+"："+p1.x+":"+p1.y)
        }
    });

    log("点击目标：",findx+temp1.getWidth()/2, findy+temp1.getHeight()/2)
    click(findx+temp1.getWidth()/2, findy+temp1.getHeight()/2)

    // if(p1){
    //     log("找到了"+p+"："+p1.x+":"+p1.y)
    //     toastLog("点击："+p1.x+temp1.getWidth()/2 + ":" + p1.y+temp1.getHeight()/2)
    //     click(p1.x+temp1.getWidth()/2,p1.y+ temp1.getHeight()/2)
    //     sleep(1000)
    // }else{
    //     log("没找到："+p);
    // }
}